
import { MenuRouter } from "@/types/menu";
import { User } from "@/types/user";
import { defineStore } from "pinia";
import { Router, RouteRecordRaw } from "vue-router";

interface System {
    router: MenuRouter[] | null // 路由
    permission:string[] // 按钮权限
    userinfo:User.UserInfo | undefined
}
export const useSystem = defineStore({
    id: "useSystem",
    // 开启持久化
    persist: {
        enabled: true,
        strategies: [
            {
                key: 'useSystem',  //自定义 Key值
                storage: sessionStorage,  // 选择存储方式
            },
        ],
    },
    state: (): System => {
        return {
            router: null,
            permission:[],
            userinfo:undefined
        }
    },
    // 数据监视，计算数据变化[有缓存]
    getters: {

    },
    actions: {
        setRouter(router: any) {
            this.router = router
        },
        async transRouter(RouterInstance: Router, routerlist: MenuRouter[]) {
            // 获取文件系统中的所有文件
            const modules = import.meta.glob('../../views/**/*.vue')
            let data = JSON.parse(JSON.stringify(routerlist))
            this.handleRouter(data,modules)
            this.addRouteItem(RouterInstance, data)
        },
        // 动态添加路由
        addRouteItem(RouterInstance: Router, routerList: MenuRouter[], pn: string = "layout") {
            if (!routerList) return false;


            for (let i = 0; i < routerList.length; i++) {
                const { path, name, component, cache, icon, link, type, children } = routerList[i]
                if (component) {
                    RouterInstance.addRoute(pn, {
                        path: path,
                        name: name,
                        component: component || undefined,
                        meta: {
                            keepalive: cache || false,
                            icon: icon || "",
                            isLink: link || false,
                            type: type || false
                        }
                    })
                }
                if (children) {
                    this.addRouteItem(RouterInstance, children, "layout")
                }
            }
        },
        // r.component = modules[`../../${r.component}`]
        // 将路由字符串路径转化为组件
        handleRouter(data: MenuRouter[],modules:any) {
            data.forEach(r =>{
                if (r.component) {
                    r.component = modules[`../../${r.component}`]
                }
                if (r.children) {
                    this.handleRouter(r.children,modules)
                }
            })
        }
    }
})